<template>
  <view class="container">
    <!-- 顶部标签栏 -->
    <view class="tab-bar-container">
      <view class="tab-bar">
        <view 
          v-for="(item, index) in tabs" 
          :key="index" 
          class="tab-item" 
          :class="{ 'active': activeIndex === index }"
          @click="switchTab(index)"
        >
          {{ item }}
          <view class="tab-indicator" v-if="activeIndex === index"></view>
        </view>
      </view>
    </view>

    <!-- 内容区域（包含轮播图和列表） -->
    <scroll-view 
      class="content-scroll-view" 
      scroll-y="true"
      enable-flex
      :show-scrollbar="false"
    >
      <view class="content-area">
        <!-- 使用transition为内容切换添加动画 -->
        <transition :name="transitionName">
          <view :key="activeIndex" class="tab-content">
            <!-- 轮播图 -->
            <swiper class="banner-swiper" 
              :indicator-dots="true" 
              :autoplay="true" 
              :interval="3000" 
              indicator-color="rgba(255, 255, 255, 0.6)"
              indicator-active-color="#007AFF">
              <swiper-item v-for="(item, index) in bannerList" :key="index">
                <image class="banner-image" :src="item.imageUrl" mode="aspectFill" />
              </swiper-item>
            </swiper>

            <!-- 内容列表 -->
            <view class="list">
              <view v-for="(item, index) in listData" :key="item.id">
                <!-- 主列表项 -->
                <view 
                  class="list-item"
                  @click="toggleExpand(index)"
                  :class="{ 'item-active': item.expanded }"
                >
                  <uni-icons class="check-icon" custom-prefix="iconfont" 
                    :type="item.expanded ? 'icon-zhankai' : 'icon-zhankai'" 
                    size="20" 
                    :color="item.expanded ? '#2A82E4' : '#E5E5E5'"
                    :style="item.expanded ? 'transform: rotate(180deg);' : ''"
                  ></uni-icons>
                  <text class="list-text">{{ item.title }}</text>
                  <view class="arrow" :class="{ 'arrow-rotate': item.expanded }"></view>
                </view>
                
                <!-- 子列表项 -->
                <transition-group name="list-transition">
                  <view class="sub-list" v-if="item.expanded" :key="'sublist-'+item.id">
                    <view 
                      v-for="(subItem, subIndex) in item.subItems" 
                      :key="subItem.id"
                      class="sub-list-item"
                      @click="toggleSelect(index, subIndex)"
                      :class="{ 'sub-item-active': subItem.selected }"
                    >
                      <uni-icons class="sub-check-icon" custom-prefix="iconfont" 
                        :type="'icon-dakai'" 
                        size="18"
                        :color="subItem.selected ? '#2A82E4' : '#E5E5E5'"
                        :style="subItem.selected ? 'transform: rotate(90deg);' : ''"
                      ></uni-icons>
                      <text class="sub-list-text">{{ subItem.title }}</text>
                    </view>
                  </view>
                </transition-group>
              </view>
            </view>
          </view>
        </transition>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed, watch } from 'vue'
import { bannerLists } from '../../src/dataResource'


// 顶部标签数据
const tabs = reactive(['课程PPT', '习题集', '案例分析', '体格检查视频'])
const activeIndex = ref(0)
const prevActiveIndex = ref(0)
const transitionName = ref('slide-left')

// 不同类型的内容数据
const contentTypes = reactive([
  { 
	id: 'ppt',
	name: '课程PPT',
	pageUrl: '/pages/content/ppt-detail'
  },
  { 
	id: 'reference',
	name: '习题集',
	pageUrl: '/pages/content/reference-detail'
  },
  {
  	id: 'case',
  	name: '案例分析'
  },
  { 
	id: 'video',
	name: '体格检查视频',
	pageUrl: '/pages/content/video-detail'
  },
  
])

// 当前内容类型
const currentContentType = computed(() => contentTypes[activeIndex.value])

// 轮播图数据 
const bannerList = ref([
  { imageUrl: bannerLists.one },
])

// 各标签的列表数据
const tabListData = reactive({
  0: [ // 课程PPT
    { 
      id: '1', 
      title: '呼吸困难', 
      expanded: false, 
      contentType: 'ppt',
      subItems: [
        
      ]
    },
    { 
      id: '2', 
      title: '胸廓与肺脏检查', 
      expanded: false, 
      contentType: 'ppt',
      subItems: []
    },
    { 
      id: '3', 
      title: '急慢性呼吸衰竭', 
      expanded: false, 
      contentType: 'ppt',
      subItems: []
    },
    { 
      id: '4', 
      title: '慢性阻塞性肺疾病', 
      expanded: false, 
      contentType: 'ppt',
      subItems: []
    },
	{
	  id: '5', 
	  title: '慢性肺源性心脏病', 
	  expanded: false, 
	  contentType: 'ppt',
	  subItems: []
	}
  ],
  1: [ // 习题集
    { 
      id: '6', 
      title: '解剖学习题', 
      expanded: false, 
      contentType: 'reference',
      subItems: [
        { id: 'r1', title: '解剖学单元测试一', selected: false },
        { id: 'r2', title: '解剖学单元测试二', selected: false }
      ]
    },
    { 
      id: '7', 
      title: '生理学习题', 
      expanded: false, 
      contentType: 'reference',
      subItems: []
    }
  ],
  2: [ // 案例分析
    { 
      id: '8', 
      title: '临床案例', 
      expanded: false, 
      contentType: 'case',
      subItems: [
        { id: 'c1', title: '呼吸系统疾病案例', selected: false },
        { id: 'c2', title: '消化系统疾病案例', selected: false }
      ]
    }
  ],
  3: [ // 体格检查视频
    { 
      id: '9', 
      title: '胸廓与肺的视诊', 
      expanded: false, 
      contentType: 'video',
      subItems: [ ]
    },
	{
	  id: '10', 
	  title: '胸廓扩张度', 
	  expanded: false, 
	  contentType: 'video',
	  subItems: [ ]
	},
	{
	  id: '11', 
	  title: '触觉语颤', 
	  expanded: false, 
	  contentType: 'video',
	  subItems: [ ]
	},
	{
	  id: '12', 
	  title: '胸膜摩擦感', 
	  expanded: false, 
	  contentType: 'video',
	  subItems: [ ]
	},
	{
	  id: '13', 
	  title: '肺部叩诊', 
	  expanded: false, 
	  contentType: 'video',
	  subItems: [ ]
	},
	{
	  id: '14', 
	  title: '肺下界移动度叩诊', 
	  expanded: false, 
	  contentType: 'video',
	  subItems: [ ]
	},
	{
	  id: '15', 
	  title: '肺部听诊', 
	  expanded: false, 
	  contentType: 'video',
	  subItems: [ ]
	}
  ]
})

// 当前显示的列表数据
const listData = ref([...tabListData[0]])

// 根据活动标签索引更新列表数据
watch(activeIndex, (newIndex) => {
  // 延迟更新列表数据，等待过渡动画完成
  setTimeout(() => {
    listData.value = [...tabListData[newIndex]]
  }, 300) // 与过渡动画持续时间一致
})

// 根据类型获取内容数据
const fetchContentByType = (contentType) => {
  console.log('加载内容类型:', contentType)
  // 这里可以添加实际的数据获取逻辑，例如从API获取数据
  // 目前使用模拟数据，所以这个函数暂时只打印日志
}

// 获取子项目数据
const fetchSubItems = (parentId, contentType) => {
  console.log(`获取 ${parentId} 的子项目，类型: ${contentType}`)
  // 这里可以添加从API获取子项目的逻辑
  // 目前使用模拟数据，所以这个函数暂时只打印日志
}

// 切换标签
const switchTab = async (index) => {
  if (index === activeIndex.value) return // 避免重复点击
  
  // 设置过渡动画方向
  transitionName.value = index > activeIndex.value ? 'slide-left' : 'slide-right'
  
  // 更新索引
  prevActiveIndex.value = activeIndex.value
  activeIndex.value = index
  
  await nextTick()
  // 根据标签加载不同类型的内容数据
  fetchContentByType(contentTypes[index].id)
}

// 切换展开/折叠状态
const toggleExpand = (index) => {
  listData.value[index].expanded = !listData.value[index].expanded
  
  // 同步更新原始数据源
  const currentTab = activeIndex.value
  const itemId = listData.value[index].id
  const originalItem = tabListData[currentTab].find(item => item.id === itemId)
  if (originalItem) {
    originalItem.expanded = listData.value[index].expanded
  }
  
  // 如果需要获取子项目数据
  if (listData.value[index].expanded && listData.value[index].subItems.length === 0) {
    fetchSubItems(listData.value[index].id, currentContentType.value.id)
  }
}

// 点击子项目，跳转到详情页
const toggleSelect = (parentIndex, childIndex) => {
  const parentItem = listData.value[parentIndex]
  const subItem = parentItem.subItems[childIndex]
  
  // 跳转到对应内容类型的详情页
  const contentType = currentContentType.value
  const url = `${contentType.pageUrl}`
  const params = {
    id: subItem.id,
    title: subItem.title,
    parentId: parentItem.id
  }
  
  console.log('准备跳转到：', url)
   
    // 原有的跳转逻辑
    try {
      const fullUrl = `${url}?id=${subItem.id}&title=${encodeURIComponent(subItem.title)}&parentId=${parentItem.id}`;
      uni.navigateTo({
        url: fullUrl,
        success: function(res) {
          console.log('跳转成功', res);
          // 更新已查看状态
          subItem.selected = true;
          
          // 同步更新原始数据源
          const currentTab = activeIndex.value
          const parentId = parentItem.id
          const childId = subItem.id
          const originalParent = tabListData[currentTab].find(item => item.id === parentId)
          if (originalParent) {
            const originalChild = originalParent.subItems.find(item => item.id === childId)
            if (originalChild) {
              originalChild.selected = true
            }
          }
        },
        fail: function(err) {
          console.error('跳转失败:', err);
          
          // 尝试用另一种方式跳转
          uni.showToast({
            title: '正在尝试其他跳转方式',
            icon: 'none',
            duration: 1000
          });
          
          setTimeout(() => {
            const pageUrl = url.replace(/^\//, '');
            uni.navigateTo({
              url: `/${pageUrl}?id=${subItem.id}&title=${encodeURIComponent(subItem.title)}&parentId=${parentItem.id}`,
              fail: (finalErr) => {
                console.error('最终跳转失败:', finalErr);
                uni.showToast({
                  title: '页面跳转失败，请检查路由配置',
                  icon: 'none'
                });
              }
            });
          }, 1000);
        }
      });
    } catch (e) {
      console.error('跳转发生异常:', e);
      uni.showToast({
        title: '跳转发生异常',
        icon: 'none'
      });
    }
  
}
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #ffffff;
}

/* 标签栏容器 */
.tab-bar-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #ffffff;
  padding: 0 0 3rpx 0; /* 为滚动线留出空间 */
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 内容滚动视图 */
.content-scroll-view {
  height: calc(100vh - 120rpx); /* 减去标签栏高度 */
  margin-top: 120rpx; /* 为固定标签栏留出空间 */
  position: relative;
  /* 隐藏滚动条 */
  overflow: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
  background-color: #ffffff;
  
  &::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
  }
}

/* 内容区域 */
.content-area {
  flex: 1;
  width: 100%;
  padding-bottom: 140rpx; /* 确保内容不被底部导航栏遮挡 */
  background-color: #ffffff;
}

/* 顶部标签栏 */
.tab-bar {
  position: relative;
  white-space: nowrap;
  border-bottom: none;
  padding: 20rpx 0;
  width: 100%;
  display: flex;
  justify-content: space-around;
}

.tab-item {
  font-size: 32rpx;
  color: #333;
  padding: 0 20rpx;
  transition: all 0.3s ease;
  position: relative;
  height: 70rpx;
  line-height: 60rpx;
  text-align: center;
  
  &.active {
    color: #2A82E4;
    font-weight: bold;
    transform: scale(1.05);
  }
  
  &:active {
    opacity: 0.7;
  }
}

/* 标签指示器 */
.tab-indicator {
  position: absolute;
  bottom: -6rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 6rpx;
  background-color: #2A82E4;
  border-radius: 6rpx;
  transition: all 0.3s ease;
  animation: indicator-enter 0.3s ease;
}

@keyframes indicator-enter {
  from {
    width: 0;
    opacity: 0;
  }
  to {
    width: 40rpx;
    opacity: 1;
  }
}

/* 轮播图 */
.banner-swiper {
  width: 100%;
  height: 300rpx;
  margin-top: 10rpx;
  padding: 0 30rpx;
  box-sizing: border-box;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 0;
}

/* 内容列表容器样式 */
.list {
  padding: 0 16rpx;
  margin-top: 20rpx;
  width: 750rpx;
  box-sizing: border-box;
  background-color: #ffffff;
}

/* 列表项样式 */
.list-item {
  position: relative;
  border-radius: 0;
  padding: 0 30rpx 0 80rpx;
  margin: 0 auto;
  display: flex;
  align-items: center;
  box-shadow: none;
  border-style: solid;
  border-color: rgba(229, 229, 229, 0.6); /* 降低边框透明度 */
  border-width: 1rpx 0 0 0; /* 减小边框宽度 */
  height: 96rpx;
  width: 688rpx;
  box-sizing: border-box;
  transition: all 0.2s ease;
  animation: list-item-enter 0.5s ease;
  animation-fill-mode: backwards; /* 确保动画开始前使用开始状态 */
  
  &:last-child:not(.expanded) {
    border-width: 2rpx 0 2rpx 0;
  }
  
  &:active {
    background-color: rgba(0, 122, 255, 0.05);
    transform: scale(0.99);
  }
}

/* 列表项动画，按顺序进入 */
@for $i from 0 through 10 {
  .list-item:nth-child(#{$i + 1}) {
    animation-delay: #{$i * 0.05}s; /* 每个列表项延迟0.05秒 */
  }
}

@keyframes list-item-enter {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 选中图标 */
.check-icon {
  position: absolute;
  left: 30rpx;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 列表文字 */
.list-text {
  font-size: 30rpx;
  color: #333;
  flex: 1;
}

/* 子列表样式 */
.sub-list {
  width: 688rpx;
  margin: 0 auto;
}

/* 子列表项样式 */
.sub-list-item {
  position: relative;
  padding: 0 30rpx 0 80rpx;
  height: 96rpx;
  display: flex;
  align-items: center;
  border-top: 1rpx solid rgba(229, 229, 229, 0.6);
  box-sizing: border-box;
  transition: all 0.2s ease;
  
  &:active {
    background-color: rgba(0, 122, 255, 0.05);
    transform: scale(0.99);
  }
}

/* 子列表项动画，按顺序进入 */
@for $i from 0 through 10 {
  .sub-list-item:nth-child(#{$i + 1}) {
    animation: sub-item-enter 0.3s ease;
    animation-delay: #{$i * 0.05 + 0.1}s; /* 每个列表项延迟0.05秒，总体延迟0.1秒 */
    animation-fill-mode: backwards;
  }
}

@keyframes sub-item-enter {
  from {
    opacity: 0;
    transform: translateX(20rpx);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 子列表选中图标 */
.sub-check-icon {
  position: absolute;
  left: 30rpx;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-zhankai{
  position: absolute;
  left: 30rpx;
  width: 40rpx;
  height: 40rpx;
}

/* 子列表文字 */
.sub-list-text {
  font-size: 30rpx;
  color: #333;
}

/* 箭头样式 */
.arrow {
  position: absolute;
  right: 30rpx;
  width: 20rpx;
  height: 20rpx;
  border-top: 2rpx solid #333;
  border-right: 2rpx solid #333;
  transform: rotate(45deg);
  transition: transform 0.3s;
  
  &-rotate {
    transform: rotate(135deg);
  }
}

/* 激活状态样式 */
.item-active {
  background-color: rgba(0, 122, 255, 0.1);
}

.sub-item-active {
  background-color: rgba(0, 122, 255, 0.1);
}

/* 列表过渡动画 */
.list-transition-enter-active,
.list-transition-leave-active {
  transition: all 0.3s ease;
  max-height: 1000rpx;
  overflow: hidden;
}

.list-transition-enter-from,
.list-transition-leave-to {
  opacity: 0;
  max-height: 0;
  transform: translateY(-10rpx);
}

/* 标签内容切换动画 */
.slide-left-enter-active,
.slide-left-leave-active,
.slide-right-enter-active,
.slide-right-leave-active {
  transition: all 0.3s ease;
  position: absolute;
  width: 100%;
  will-change: transform, opacity; /* 优化动画性能 */
}

.slide-left-enter-from {
  opacity: 0;
  transform: translateX(100%);
}

.slide-left-leave-to {
  opacity: 0;
  transform: translateX(-100%);
}

.slide-right-enter-from {
  opacity: 0;
  transform: translateX(-100%);
}

.slide-right-leave-to {
  opacity: 0;
  transform: translateX(100%);
}

.tab-content {
  width: 100%;
  position: relative;
}
</style>